require 'erubis'
require 'open-uri'

module Dior
  class Context
    include Helpers

    def initialize(config)
      @registry = Registry.new
      load_external_dependencies(config.dependencies)
    end

    def evaluate(template)
      Erubis::Eruby.new(template, pattern: '` `').result(binding)
    end

    def component(name, dependencies = [], global: false, &block)
      component = Component.new(name, dependencies, global: global, &block)
      @registry << component
    end
    alias register_component component

    def each_component
      return enum_for(:each_component) unless block_given?
      @registry.each { |component| yield component }
    end

    private

    def load_external_dependencies(specs)
      specs.each do |spec|
        content = open(spec[:uri], &:read)
        register_component(spec[:name], spec[:dependencies], global: true) { content }
      end
    end
  end
end